﻿Imports System.Configuration
Imports System.Deployment.Application
Imports System.IO
Imports System.Resources
Imports System.Web
Imports System.Xml

Public Class BaseTcSMES
#Region "Property"

    '資料庫類型
    Protected Property DataBaseType As String
    '資料庫連線字串
    Protected Property ConnectionString As String
    Protected Property objSMES As New tcSMES.clsSMES
    Protected Property Utility As New tcSMES.Utility
    Protected Property AccountID As String = String.Empty
    Protected Property objLic As New iMESLicxManager.clsDBCom
    'add by vincentddman 20180614 增加多語系處理緩存字典 start
    Dim languageDic As Dictionary(Of String, String)
    ''' <summary>
    ''' 獲取對應的多語言訊息字典
    ''' </summary>
    ''' <returns></returns>
    Private ReadOnly Property LanguageDictionary As Dictionary(Of String, String)
        Get
            '延遲加載
            If (IsNothing(languageDic)) Then
                languageDic = New Dictionary(Of String, String)
                Dim strSQL As String
                Dim dtTBLMULTILLANGUAGE As DataTable
                Dim daTemp As OleDb.OleDbDataAdapter
                Dim cn As OleDb.OleDbConnection
                Dim cmd As OleDb.OleDbCommand
                Dim LanguageMode As String = "zn-chs"

                '出錯 預設簡體中文
                Try
                    LanguageMode = System.Configuration.ConfigurationManager.AppSettings.Get("LanguageMode")
                Catch ex As Exception
                    LanguageMode = "zn-chs"
                End Try

                '獲取當前語言別的多語言信息
                strSQL = "select * from TBLMULTILLANGUAGE where langtype = '" & LanguageMode & "'"
                Try
                    '取得TBLMULTILLANGUAGE 資料
                    cn = objLic.CreateConnection(ConnectionString)
                    cmd = New OleDb.OleDbCommand(String.Empty, cn)
                    cmd.CommandText = modTC.SQLCommandTuning(DataBaseType, strSQL)

                    daTemp = New OleDb.OleDbDataAdapter(cmd)
                    dtTBLMULTILLANGUAGE = New DataTable("TBLMULTILLANGUAGE")
                    daTemp.Fill(dtTBLMULTILLANGUAGE)

                    For Each singleRow As DataRow In dtTBLMULTILLANGUAGE.Rows
                        Try
                            languageDic.Add(singleRow("LANGKEY"), singleRow("LANGVALUE"))
                        Catch ex As Exception
                            Continue For
                        End Try
                    Next
                Catch ex As Exception

                Finally
                    cmd = Nothing
                End Try
            End If
            Return Me.languageDic
        End Get
    End Property
    'add by vincentddman 20180614 增加多語系處理緩存字典 end
#End Region

    Public Sub New()
        '取出資料庫類型
        Me.DataBaseType = objLic.GetDataBaseType
        '取出資料庫連線字串
        Me.ConnectionString = objLic.GetConnectionString(Me.DataBaseType)
    End Sub
    Protected Function CreateConnection() As OleDb.OleDbConnection
        Return objLic.CreateConnection(ConnectionString)
    End Function

#Region "数据库操作"
    Protected Function querySQL(ByVal strSQL As String) As OleDb.OleDbDataReader
        '開啟資料庫連線

        Dim cn As OleDb.OleDbConnection = CreateConnection()
        Dim cmd As OleDb.OleDbCommand
        cmd = New OleDb.OleDbCommand(Utility.SQLCommandTuning(DataBaseType, strSQL.ToString), cn)
        Return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
    End Function
#End Region
#Region "--- Others ---"

    Public Function ChkSingleQuation(ByVal SingleString As String) As String

        '//將包含單引號的字串轉為可存入的字串

        Dim i As Integer
        Dim j As Integer
        Dim tmpLeft As String
        Dim tmpRight As String
        Dim tmpResult As String

        Try
            If SingleString = "" Then
                ChkSingleQuation = SingleString
            Else
                If InStr(1, SingleString, "'") <> 0 Then
                    j = 0
                    tmpResult = SingleString

                    For i = 1 To Len(SingleString)
                        If Mid(SingleString, i, 1) = "'" Then
                            tmpLeft = Mid(tmpResult, 1, i + j)
                            tmpRight = Mid(tmpResult, i + j + 1, Len(tmpResult) - i - j)
                            tmpResult = tmpLeft & "'" & tmpRight
                            j = j + 1
                        End If
                    Next i
                    ChkSingleQuation = tmpResult
                Else
                    ChkSingleQuation = SingleString
                End If
            End If

        Catch e1 As Exception
            '發生錯誤時丟回本身的Function Name及系統錯誤訊息
            Throw 'New Exception("modTC.ChkSingleQuation: " & e1.Message)

        End Try

    End Function

    'add by vincentddman 20180614 增加多語系處理 start
    ''' <summary>
    ''' 轉換多語系
    ''' </summary>
    ''' <param name="key">langekey</param>
    ''' <returns>langevalue</returns>
    Public Function MultilLanguage(ByVal key As String) As String

        Dim ReturnStrimg As String = key

        Try
            LanguageDictionary.TryGetValue(key, ReturnStrimg)
        Catch ex As Exception
            ReturnStrimg = key
        End Try

        Return ReturnStrimg
    End Function
    'add by vincentddman 20180614 增加多語系處理 end

    Public Function checkPassword(ByVal UserNo As String, ByVal Password As String) As Boolean
        Dim objUSRSecurity As New kcUSR.clsUSRSecurity
        Dim strSQL As String = ""
        Dim cnnTemp As OleDb.OleDbConnection
        Dim daTemp As OleDb.OleDbDataAdapter
        Dim cmmTemp As OleDb.OleDbCommand
        Dim dtTemp As New DataTable
        checkPassword = False
        Try
            cnnTemp = objLic.CreateConnection(ConnectionString) 'Create connection

            strSQL = " Select PASSWORD From TBLUSRUSERBASIS  " &
             " Where USERNO='" & UserNo & "' "
            dtTemp = New DataTable("QueryProcess")
            cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp)
            daTemp = New OleDb.OleDbDataAdapter(cmmTemp)
            daTemp.Fill(dtTemp)
            If dtTemp.Rows.Count > 0 Then
                Dim passwordEcording = PasswordEncoding(Password)
                objUSRSecurity.chkPassword(UserNo, passwordEcording, dtTemp.Rows(0)("PASSWORD").ToString)
                checkPassword = True
            Else
                Throw New Exception("[%UserNo%] [%is not exist%]:" & UserNo & "!")
            End If
        Catch ex As Exception
            checkPassword = False
            Throw
        Finally
            objLic.CloseConnection(cnnTemp)
            cnnTemp = Nothing
            If Not dtTemp Is Nothing Then
                dtTemp.Dispose()
            End If
        End Try
        Return checkPassword
    End Function

    Public Shared Function PasswordEncoding(ByRef Password As String) As String
        '此 Function 將傳入值加以編碼後傳出,編碼後長度不變
        '傳入值: 密碼
        '傳回值: 編碼後密碼

        'Vernam密碼是由Gilbert Vernam在1918年發明的
        Dim g_Key As String = "xNDFz6LH67LOv7xKbWFpbMu1wejrM7SzvV4tLRvq3X47m708O1xMHLoaMNCqGhoaEN"
        Dim strChar, iCryptChar, strEncrypted As String
        Dim i, iKeyChar, iStringChar As Integer

        For i = 1 To Len(Password)
            iKeyChar = Asc(Mid(g_Key, i, 1))
            iStringChar = Asc(Mid(Password, i, 1))
            iCryptChar = iKeyChar Xor iStringChar
            strEncrypted = strEncrypted & Chr(iCryptChar)
        Next

        PasswordEncoding = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted))

    End Function
#End Region

#Region "SMES专用"
    '//^_^ ADD BY H-03274  20190322 =============begin============== 
    ''' <summary>
    ''' 新架構使用 檢查SessionID
    ''' 0051006: 我的最愛資訊取得/今日生產任務/工位機生產批取得 添加 sessioid 檢查
    ''' </summary>
    ''' <param name="SessionID"></param>
    ''' <param name="pException"></param>
    ''' <returns></returns>
    Public Function CheckSessionID_sMES(ByVal SessionID As String, ByRef pException As List(Of ArrayList)) As Boolean
        CheckSessionID_sMES = False

        Dim cnnTemp As OleDb.OleDbConnection
        Dim cmmTemp As OleDb.OleDbCommand
        Dim drTemp As OleDb.OleDbDataReader
        Dim strSQL As String = "Select * From tblLoginInfo Where SessionID = '" & SessionID & "' "

        Try
            cnnTemp = objLic.CreateConnection(objLic.GetConnectionString(objLic.GetDataBaseType)) 'Create connection
            cmmTemp = New OleDb.OleDbCommand(strSQL, cnnTemp)
            drTemp = cmmTemp.ExecuteReader()
            If Not drTemp.Read Then
                CheckSessionID_sMES = False
                combineException(strException:=pException, mesmsg:="[%CheckSessionID fail%],[%IllegalSession%]")
                'Throw New Exception("CheckSessionID fail!", New Exception("[%IllegalSession%]"))
            Else
                'Update Seesion資料避免被刪除
                strSQL = "Update tblLoginInfo Set R_IDLETIME = To_Date('" & Format(CDate(Now), "yyyy/MM/dd H:mm:ss") &
                    "','YYYY/MM/DD HH24:MI:SS') Where SessionID = '" & SessionID & "' "
                Call ExecuteSQLNoneQuery(objLic.GetDataBaseType, objLic.GetConnectionString(objLic.GetDataBaseType), strSQL)
                CheckSessionID_sMES = True
            End If
            cmmTemp.Dispose()
            drTemp.Close()
        Catch ex As Exception
            If Not IsNothing(pException) Then
                combineException(strException:=pException, mesmsg:=ex.Message)
            Else
                Throw ex
            End If
        Finally
            Call objLic.CloseConnection(cnnTemp)
        End Try

        Return CheckSessionID_sMES

    End Function

    Public Sub combineException(ByRef strException As List(Of ArrayList), Optional ByVal code As String = Nothing,
        Optional ByVal sysmsg As String = Nothing, Optional ByVal mesmsg As String = Nothing, Optional ByVal stack As String = Nothing)
        Dim result As Boolean = False
        Try
            Dim al As New ArrayList
            al.Add(code)
            al.Add(sysmsg)
            al.Add(mesmsg)
            al.Add(stack)
            strException.Add(al)
            result = True
        Catch ex As Exception
            result = False
        End Try

    End Sub

    ''' <summary>
    ''' 將MES後端所丟出的MESException, 將ErrorCode及ErrorMessage轉換成相對應的訊息後傳回
    ''' </summary>
    ''' <param name="ex"></param>
    ''' <returns></returns>
    Public Function GenerateMESExceptionMessage(ex As iMESException.MESException) As String

        Dim errname As String = ""
        Dim action As String = ""
        Dim message As String = ""

        funTranslate(ex.ErrorCode, ex.Message, errname, action, message)

        'Return errname & vbCrLf & message
        Return ex.ErrorCode & vbCrLf & ex.Message
    End Function

    Private Function funTranslate(ByVal ErrorCode As String, ByVal ErrorMessage As String,
        ByRef ErrName As String, ByRef ErrAction As String, ByRef ErrMessage As String) As String

        Dim LanguageMode As String

        Try

            LanguageMode = System.Configuration.ConfigurationManager.AppSettings("LanguageMode")

            ' Check LanguageMode
            Dim strMsgFile, strMsgActionFile, strGenFile As String
            If LanguageMode = "" Then
                strMsgFile = "msg_name"
                strMsgActionFile = "msg_action"
                strGenFile = "mesresource"
            Else
                strMsgFile = "msg_name." & LanguageMode
                strMsgActionFile = "msg_action." & LanguageMode
                strGenFile = "mesresource." & LanguageMode
            End If

            '2.Get File Path
            Dim strResourcePath As String
            Dim strResourceDirectory As String = System.Configuration.ConfigurationManager.AppSettings("ResourceDir")

            If (HttpContext.Current Is Nothing) Then
                strResourcePath += System.Windows.Forms.Application.StartupPath & "\" & strResourceDirectory
            Else
                strResourcePath += HttpContext.Current.Server.MapPath("./" & "wsUpdateResource/" & strResourceDirectory)
            End If

            '檢查檔案是否存在
            If Dir(strResourcePath & "\" & strMsgFile & ".resources") = "" Then  'File not exist
                'MsgBox(strResourcePath & "\" & strMsgFile & ".resources is not exist,ChgTranslateName_Msg failed!!", MsgBoxStyle.Exclamation)
                Exit Function
            End If
            If Dir(strResourcePath & "\" & strGenFile & ".resources") = "" Then  'File not exist
                'MsgBox(strResourcePath & "\" & strGenFile & ".resources is not exist,ChgTranslateName_Msg failed!!", MsgBoxStyle.Exclamation)
                Exit Function
            End If

            '3.Get ErrorName by ErrorCode
            Dim rmErrName As ResourceManager = ResourceManager.CreateFileBasedResourceManager(strMsgFile, strResourcePath, Nothing)
            Dim strErrName As String
            Try
                strErrName = rmErrName.GetString(ErrorCode.ToUpper)
                If strErrName = "" Then strErrName = ErrorCode
            Catch ex As Exception
                strErrName = ErrorCode
            End Try
            rmErrName = Nothing

            '4.Get Action
            Dim rmErrAction As ResourceManager = ResourceManager.CreateFileBasedResourceManager(strMsgActionFile, strResourcePath, Nothing)
            Dim rmGen As ResourceManager = ResourceManager.CreateFileBasedResourceManager(strGenFile, strResourcePath, Nothing)
            Dim strErrAction As String
            Try
                strErrAction = rmErrAction.GetString(ErrorCode.ToUpper)
                'Modify By Acer 2007/07/02
                'If strErrAction = "" Then strErrAction = "Not Define"
                If strErrAction = "" Then strErrAction = rmGen.GetString("NOT DEFINE")
            Catch ex As Exception
                'strErrAction = "Not Define"
                strErrAction = rmGen.GetString("NOT DEFINE")
            End Try
            rmErrAction = Nothing
            'rmGen = Nothing

            '5.Message [%%] Replace
            'Modify By Acer 2007/07/02
            'Dim rmGen As ResourceManager = ResourceManager.CreateFileBasedResourceManager(strGenFile, strResourcePath, Nothing)
            'rmGen = ResourceManager.CreateFileBasedResourceManager(strGenFile, strResourcePath, Nothing)
            Dim strErrMessage, strKey, strKeyValue As String
            Dim intStart, j, k, l As Integer
            Dim KeyIsExist As Boolean = False


            intStart = 1
            j = 1

            Do While j <> 0
                j = InStr(intStart, ErrorMessage, "[%", CompareMethod.Text)
                If j = 0 Then
                    strErrMessage += Mid(ErrorMessage, intStart)
                Else
                    k = InStr(j + 2, ErrorMessage, "%]", CompareMethod.Text)
                    If k = 0 Then
                        '找不到對應的結束字元.
                        strErrMessage += Mid(ErrorMessage, intStart)
                        j = 0
                    Else
                        '檢查是否有不對稱的情況.
                        l = InStr(j + 2, ErrorMessage, "[%", CompareMethod.Text)
                        If l = 0 OrElse l > k Then
                            strErrMessage += Mid(ErrorMessage, intStart, j - intStart)
                            strKey = Mid(ErrorMessage, j + 2, k - j - 2)
                            '將Key執行語系轉換
                            Try
                                ' 處理多個語系檔
                                For Each f As String In My.Computer.FileSystem.GetFiles(strResourcePath, FileIO.SearchOption.SearchTopLevelOnly, strGenFile & ".resources*").OrderByDescending(Function(x) x)

                                    KeyIsExist = False

                                    If File.Exists(f) = True Then

                                        Dim fs As New FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read)
                                        Dim rmGen2 As New ResourceSet(fs)
                                        fs.Close()

                                        strKeyValue = rmGen2.GetString(strKey.ToUpper)
                                        If strKeyValue IsNot Nothing Then
                                            KeyIsExist = True
                                        End If

                                        rmGen2.Close()
                                        rmGen2 = Nothing

                                    End If

                                    If (KeyIsExist) Then
                                        Exit For
                                    End If

                                Next

                            Catch ex As Exception
                                strKeyValue = strKey
                            End Try
                            If strKeyValue = "" Then
                                strErrMessage += strKey
                            Else
                                strErrMessage += strKeyValue
                            End If
                            '下次截取字串的起始位置
                            intStart = k + 2
                        Else
                            '不對稱,找到最內層的[%%]
                            Dim m As Integer
                            '在前面的條件下,一定找得到.
                            m = InStrRev(ErrorMessage, "[%", k, CompareMethod.Text)
                            '擷出不轉換的字串.
                            strErrMessage += Mid(ErrorMessage, intStart, m - intStart)
                            strKey = Mid(ErrorMessage, m + 2, k - m - 2)
                            '將Key執行語系轉換
                            Try
                                For Each f As String In My.Computer.FileSystem.GetFiles(strResourcePath, FileIO.SearchOption.SearchTopLevelOnly, strGenFile & ".resources*").OrderByDescending(Function(x) x)

                                    KeyIsExist = False

                                    If File.Exists(f) = True Then

                                        Dim fs As New FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read)
                                        Dim rmGen2 As New ResourceSet(fs)
                                        fs.Close()

                                        strKeyValue = rmGen2.GetString(strKey.ToUpper)
                                        If strKeyValue IsNot Nothing Then
                                            KeyIsExist = True
                                        End If

                                        rmGen2.Close()
                                        rmGen2 = Nothing

                                    End If

                                    If (KeyIsExist) Then
                                        Exit For
                                    End If

                                Next
                            Catch ex As Exception
                                strKeyValue = strKey
                            End Try
                            If strKeyValue = "" Then
                                strErrMessage += strKey
                            Else
                                strErrMessage += strKeyValue
                            End If
                            '下次截取字串的起始位置
                            intStart = k + 2
                        End If
                    End If
                End If
            Loop


            rmGen = Nothing

            If strErrMessage = "" Then strErrMessage = ErrorMessage

            'Return
            ErrName = strErrName
            ErrAction = strErrAction
            ErrMessage = strErrMessage

        Catch ex As Exception
        End Try

    End Function

    ''' <summary>
    ''' 將Exception內容轉成字串
    ''' </summary>
    ''' <param name="pException"></param>
    ''' <returns></returns>
    Public Function generateException(ByVal pException As List(Of ArrayList)) As String

        Dim result As String = ""

        pException.ForEach(Sub(x As ArrayList)
                               If (x.Item(1) & "" <> "") Then
                                   result += Utility.TranslateMsg(x.Item(1) & "") & "; "
                               End If
                               If (x.Item(2) & "" <> "") Then
                                   result += Utility.TranslateMsg(x.Item(2) & "") & "; "
                               End If
                           End Sub)

        result = result.TrimEnd(New Char() {" ", ";"})

        Return result

    End Function
    '//^_^ ADD BY H-03274  20190322 ==============END===============
#End Region


End Class
